package com.heima.comment.service.impl;

import com.heima.common.exception.CustomException;
import com.heima.comment.service.CommentRepayService;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 查看更多回复内容
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {

        //1. 参数校验://是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //校验文章id   校验内容不为空  校验内容长度不能大于140个字符 (validated校验)
        if (dto.getCommentId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //        校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //    评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        //    2. 条件查询评论回复信息
        Date date = dto.getMinDate();
//        Date date = new Date();
//        if (dto.getMinDate() == null) {
//            date=new Date();
//        }
        Integer pageSize;
        pageSize = dto.getSize();
        if (pageSize == null) {
            pageSize = 5;
        }
        //条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(date)
        ).limit(pageSize).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> list = mongoTemplate.find(query, ApCommentRepay.class);
        //  未登录//3.1 如果未登录直接 返回评论回复列表
        if (user.getId()==0) {
            return ResponseResult.okResult(list);
        }
	    //3.2 如果登录，需要判断哪些回复点过赞
        // get 登录人id 查询回复点赞列表
        ArrayList<ApCommentRepayVO> apCommentRepayVOS = new ArrayList<>();
        query = Query.query(Criteria.where("authorId").is(user.getId()));
        List<ApCommentRepayLike> userCommentRepayLikelist = mongoTemplate.find(query, ApCommentRepayLike.class);
        for (ApCommentRepay apCommentRepay : list) {
            ApCommentRepayVO repayLike = new ApCommentRepayVO();
            BeanUtils.copyProperties(apCommentRepay,repayLike);
            for (ApCommentRepayLike apCommentRepayLike : userCommentRepayLikelist) {
                if (apCommentRepayLike.getCommentRepayId() .equals(apCommentRepay.getId()) ) {
                    repayLike.setOperation((short)0);
                }
            }
            apCommentRepayVOS.add(repayLike);
        }
//        query = Query.query(Criteria.where("commentId").is(dto.getCommentId());


	    //思路:
	    //     基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
	    //     遍历 当前回复列表，将每一个回复信息 封装成 vo
	    //     判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理

        return ResponseResult.okResult(apCommentRepayVOS);
    }
    /**
     * 保存回复
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //1. 参数校验://是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //校验文章id   校验内容不为空  校验内容长度不能大于140个字符 (validated校验)
        if (dto.getCommentId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //        校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //回复内容安全校验
        //TODO:阿里云内容检查

       //简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**

        //2. 根据评论id查询评论信息  检查是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment one = mongoTemplate.findOne(query, ApComment.class);
        //评论数据不存在
        if (one == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"评论数据不存在");
        }
        //3. 保存评论回复信息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
//
        //4. 修改评论信息中回复数量 + 1
        query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        Integer count = apComment.getReply()+1;
        apComment.setReply(count);
        mongoTemplate.save(apComment);
        HashMap<String, Integer> map = new HashMap<>();
        map.put("repay",count);
        return ResponseResult.okResult(map);

    }

    /**
     * 点赞回复的评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 参数校验://是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //     回复id不能为空   operation 必须 0 或 1
        if (dto.getCommentRepayId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //        校验是否登录( 必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //     校验回复信息是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
        ApCommentRepay one0 = mongoTemplate.findOne(query, ApCommentRepay.class);
        ApCommentRepayLike one = null;
        if (one0 == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"评论的回复不存在");
        }
        //     2. 如果是点赞  判断是否点过赞  0 点赞
        Integer likes ;
        //获取用户ID
        Integer userId = AppThreadLocalUtils.getUser().getId();
        if (dto.getOperation() == 0) {
            query = Query.query(Criteria.where("authorId").is(userId).and("commentRepayId").is(dto.getCommentRepayId()));
            one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
            if (one == null) {
                //未点过赞   保存点赞信息到mongo
                ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
                apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
                apCommentRepayLike.setAuthorId(userId);
                mongoTemplate.insert(apCommentRepayLike);
                //并修改评论信息的点赞数量( + 1)
                query = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
                ApCommentRepay two = mongoTemplate.findOne(query, ApCommentRepay.class);
                likes = two.getLikes()+1;
                two.setLikes(likes);
                mongoTemplate.save(two);
                HashMap<String, Integer> map = new HashMap<>();
                map.put("likes",likes);
                return ResponseResult.okResult(map);
            }
            //点过赞提示 请勿重复点赞
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"已经点赞过");
        }
        //4. 如果是取消点赞操作
        query = Query.query(Criteria.where("authorId").is(userId).and("commentRepayId").is(dto.getCommentRepayId()));
        one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (one == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"没有点赞过");
        }
        //删除点赞信息
        mongoTemplate.remove(one);
        //并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
        query = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
        ApCommentRepay two = mongoTemplate.findOne(query, ApCommentRepay.class);
        likes = two.getLikes()-1<0?0:two.getLikes()-1;
        two.setLikes(likes);
        mongoTemplate.save(two);
//
        //5. 返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
        HashMap<String, Integer> map = new HashMap<>();
        map.put("likes",likes);
        return ResponseResult.okResult(map);

    }
}
